package com.tebiecloud.yunst.server.controller.feign;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.HttpClient;
import com.tebiecloud.common.utils.IdentityNoUtils;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.yunst.client.constants.ResultEnum;
import com.tebiecloud.yunst.client.model.entity.YunStUser;
import com.tebiecloud.yunst.client.model.yunst.IDGenerator;
import com.tebiecloud.yunst.client.service.IYunStUserServiceClient;
import com.tebiecloud.yunst.server.service.YunStUserService;
import com.tebiecloud.yunst.server.utils.UrlUtils;
import com.tebiecloud.yunst.server.yunstservice.YunStService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/feign/yunstuser")
public class YunUserController implements IYunStUserServiceClient {

    //校验手机号正则表达式
    private static  String PHONE_NUMBER_REG = "^(1[3-9])\\d{9}$";

    @Autowired
    private YunStUserService yunStUserService;

    @Autowired
    private YunStService yunStService;

    @Value("${tebiecloud.yunst.jumpUrl}")
    private String jumpUrl;

    @Value("${tebiecloud.yunst.backUrl}")
    private String backUrl;

    @Value("${tebiecloud.yunst.urlTager}")
    private String urlTager;

    @GetMapping("create")
    @Override
    public ResultBody create(){
        String bizUserId = IDGenerator.generateGUID();
        bizUserId = yunStService.createMember(bizUserId,"3","1");
        return ResultBodyUtils.ok(bizUserId);
    }

    @PostMapping("realName")
    @Override
    public ResultBody realName(
            @RequestParam(value = "bizUserId") String bizUserId,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "identityNo") String identityNo
    ) {
        //校验身份证是否正确
        if(!IdentityNoUtils.isIdentityNo(identityNo)){
            return ResultBodyUtils.build(ResultEnum.YUN_ST_USER_IDENTITYNO_ERROR.getCode(), ResultEnum.YUN_ST_USER_IDENTITYNO_ERROR.getMessage());
        }
        YunStUser entity = new YunStUser();
        entity.setBizUserId(bizUserId);
        entity.setName(name);
        entity.setIdentityNo(identityNo);
        YunStUser yunStUser = getEntityByBizUserId(bizUserId);
        //查询不存在
        if(yunStUser==null)return  ResultBodyUtils.build(ResultEnum.YUN_ST_USER_NOT_FIND.getCode(),ResultEnum.YUN_ST_USER_NOT_FIND.getMessage());
        //已经实名
        if(StringUtils.isNotEmpty(yunStUser.getIdentityNo())) {
            return ResultBodyUtils.build(ResultEnum.YUN_ST_USER_REAL_NAME.getCode(), ResultEnum.YUN_ST_USER_REAL_NAME.getMessage());
        }
        Map<String,String> resultMap = yunStUserService.realName(entity);
        if(resultMap.get("status").equals("OK")){
            return ResultBodyUtils.ok();
        }
        return ResultBodyUtils.build(Integer.valueOf(resultMap.get("code")),resultMap.get("message"));
    }

    @PostMapping("applyBindAcct")
    @Override
    public ResultBody applyBindAcct(
            @RequestParam(value = "bizUserId") String bizUserId,
            @RequestParam(value = "acctType") String acctType,
            @RequestParam(value = "acct") String acct
    ) {
        YunStUser yunStUser = getEntityByBizUserId(bizUserId);
        //查询不存在
        if(yunStUser==null)return  ResultBodyUtils.build(ResultEnum.YUN_ST_USER_NOT_FIND.getCode(),ResultEnum.YUN_ST_USER_NOT_FIND.getMessage());
        //已经绑定用户标识
        if(StringUtils.isNotEmpty(yunStUser.getAcct())) {
            return ResultBodyUtils.build(ResultEnum.YUN_ST_USER_ACCT.getCode(), ResultEnum.YUN_ST_USER_ACCT.getMessage());
        }
        Map<String,String> resultMap = yunStUserService.applyBindAcct(bizUserId,acctType,acct);
        if(resultMap.get("status").equals("OK")){
            return ResultBodyUtils.ok();
        }
        return ResultBodyUtils.build(Integer.valueOf(resultMap.get("code")),resultMap.get("message"));
    }

    @GetMapping("signContract")
    @Override
    public ResultBody signContract(
            @RequestParam(value = "bizUserId") String bizUserId){
//        YunStUser yunStUser = getEntityByBizUserId(bizUserId);
//        //查询不存在
//        if(yunStUser==null)return  ResultBodyUtils.build(ResultEnum.YUN_ST_USER_NOT_FIND.getCode(),ResultEnum.YUN_ST_USER_NOT_FIND.getMessage());
//        if(yunStUser.getSignContract().equals(1)) {
//            return ResultBodyUtils.build(ResultEnum.YUN_ST_USER_SIGNCONTRACT.getCode(), ResultEnum.YUN_ST_USER_SIGNCONTRACT.getMessage());
//        }
        String signJumpUrl = jumpUrl+"/yunst/yunstuser/signcontract/update";
        String signBackUrl = backUrl+"/yunst/yunstuser/signcontract/update";
        String url = yunStService.signContract(bizUserId,signJumpUrl,signBackUrl);
        String sysid = UrlUtils.parse(url).params.get("sysid");
        HttpClient httpClient = new HttpClient();
        String params = "/service/soa/MemberServlet.do?sysid=" + sysid + "&jumpUrl=" + signJumpUrl + "&backUrl=" + signBackUrl +
                "&bizUserId=" +bizUserId + "&source=2&action=signContract";
        String result = httpClient.GET(urlTager+params);
        System.out.println(JSON.parseObject(result).get("status"));
        System.out.println("url=" +url);
        return ResultBodyUtils.ok(urlTager+params);
    }
    @GetMapping("sendVerificationCode")
    @Override
    public ResultBody sendVerificationCode(
            @RequestParam(value = "bizUserId") String bizUserId,
            @RequestParam(value = "phone") String phone){
        if(StringUtils.isEmpty(phone)&&!phone.matches(PHONE_NUMBER_REG)){
            return ResultBodyUtils.build(ResultEnum.YUN_ST_USER_PHONE_ERROR.getCode(), ResultEnum.YUN_ST_USER_PHONE_ERROR.getMessage());
        }
        Map<String,String> resultMap = yunStUserService.sendVerificationCode(bizUserId,phone);
        if(resultMap.get("status").equals("OK")){
            return ResultBodyUtils.ok();
        }
        return ResultBodyUtils.build(Integer.valueOf(resultMap.get("code")),resultMap.get("message"));
    }

    @PostMapping("bindPhone")
    @Override
    public ResultBody bindPhone(@RequestParam(value = "bizUserId") String bizUserId,
                                @RequestParam(value = "phone") String phone,
                                @RequestParam(value = "bizUserId") String verificationCode){
        if(StringUtils.isEmpty(phone)&&!phone.matches(PHONE_NUMBER_REG)){
            return ResultBodyUtils.build(ResultEnum.YUN_ST_USER_PHONE_ERROR.getCode(), ResultEnum.YUN_ST_USER_PHONE_ERROR.getMessage());
        }
        Map<String,String> resultMap = yunStUserService.bindPhone(bizUserId,phone,verificationCode);
        if(resultMap.get("status").equals("OK")){
            return ResultBodyUtils.ok();
        }
        return ResultBodyUtils.build(Integer.valueOf(resultMap.get("code")),resultMap.get("message"));
    }
    /**
     * 私用查询用户是否存在
     * @param bizUserId
     * @return
     */
    private YunStUser getEntityByBizUserId(String bizUserId){
        QueryWrapper<YunStUser> queryWrapper = new QueryWrapper<YunStUser>();
        queryWrapper.eq("biz_user_id",bizUserId);
        return yunStUserService.getOne(queryWrapper);
    }
}
